package com.eusoft.demo.interceptor;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.log.Log;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.eusoft.demo.utils.JWTUtils;
import com.eusoft.demo.utils.ResultUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author eusoft
 * @since 2021-10-12
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println(1);
        String msg = "";
        try {
            if(!token.equals("null")) {
                JWTUtils.verify(token);
            }
            System.out.println(2);
            return true;
        } catch (TokenExpiredException e) {
            msg = "Token已经过期!!!";
        } catch (SignatureVerificationException e) {
            msg = "签名错误!!!";
        } catch (AlgorithmMismatchException e) {
            msg ="加密算法不匹配!!!";
        } catch (Exception e) {
            msg ="无效token~~";
            e.printStackTrace();
        }
        //map转string字符串
        System.out.println(3);
        String json = new ObjectMapper().writeValueAsString(ResultUtils.error(msg));
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

}
